<template>
    <div class="main-content">
        <levelbar></levelbar>
        <echartsLayout :formState='formState' :dataListState='dataListState' :eCharts1State='eCharts1State' :eCharts2State='eCharts2State' 
        :eCharts3State='eCharts3State' :chartsListState='chartsListState' :tableState='tableState'>
            <div slot="form">
                <el-form :model="formInline" ref="formInline" label-width="80px">
                    <el-row :gutter="41">
                         <el-col :span="7">
                            <el-form-item label="省份" prop="provinceId">
                                <province v-model="formInline.provinceId" :name.sync="formInline.provinceName"></province>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="市区" prop="cityId">
                                <city v-model="formInline.cityId" :province="formInline.provinceId" :name.sync="formInline.cityName"></city>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="区县" prop="areaId">
                                <region v-model="formInline.areaId" :city="formInline.cityId" :name.sync="formInline.areaName"></region>
                            </el-form-item>
                        </el-col>
                    </el-row> 
                   <el-row :gutter="41">
                        <el-col :span="7">
                            <el-form-item label="学校名称" prop="schoolName">
                                <school v-model="formInline.schoolName" style="width:100%"
                                @change='schoolChange'></school>
                            </el-form-item>
                        </el-col>
                   
                       <el-col :span="7">
                           <el-form-item label="时间范围">
                            <el-select v-model="formInline.time" placeholder="请选择时间范围" @change="changeTime"
                            style="width:100%">
                                    <el-option v-for="(item,index) in timeArrs" 
                                    :key="index" :label="item.timeName" :value="item.timeId"> 
                                    </el-option>
                            </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3" :offset="7">
                            <div class="top-line">
                                <el-button type="primary" class="btn-common" @click="submit">查询</el-button>
                            </div>
                        </el-col>
                    </el-row> 
                </el-form>
            </div> 
            <div slot="dataList"  v-loading="loading">
                <el-row :gutter="20">
                    <el-col :span="6" class="data-item">
                        <div class="item">
                            <div class="title">开通学校数</div>
                            <div class="data">{{schoolNum}}</div> 
                        </div>
                    </el-col>
                    <el-col :span="6" class="data-item">
                        <div class="item">
                            <div class="title">购买总人数</div>
                            <div class="data">{{buyNum}}</div> 
                        </div>
                    </el-col> 
                    <el-col :span="6" class="data-item">
                        <div class="item">
                            <div class="title">观看总次数</div>
                            <div class="data">{{viewNum}}</div> 
                        </div>
                    </el-col>
                     <el-col :span="6" class="data-item">
                        <div class="item">
                            <div class="title">观看总时长</div>
                            <div class="data" :class="{'dataLong':viewTime!=0}">{{viewTime}}</div> 
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div slot="eCharts1"  v-loading="loading">
                <div class="charts-title">空中课堂统计对比图</div>
                <div class="charts-display">
                   <trendChart width='100%' height='100%' id="trendChart2" :option='trendChart2Option'></trendChart>
                </div>
            </div>
        </echartsLayout>
    </div>
</template>

<script>
    import Levelbar from '../../layout/Levelbar';
    import { mapState, mapGetters } from 'vuex';
    import echartsLayout from 'components/TableLayout/echartsLayout'; 
    import trendChart from 'components/Charts/trendChart';
    import province from 'components/CascadeRegion/province';
    import city from 'components/CascadeRegion/city';
    import region from 'components/CascadeRegion/region';
    import moment from 'moment';
    import school from 'components/SchoolClasss/school';
    import {queryTable} from 'api/common';
    export default{
        components: { province, city, region, echartsLayout, Levelbar, trendChart, school},
        data() {
            return {
                schoolNum: 0, // 开通学校数
                buyNum: 0, // 购买总人数
                viewNum: 0, // 观看人数
                viewTime: 0, // 观看时长
                formState: false,
                dataListState: false,
                eCharts1State: false,
                eCharts2State: false,
                eCharts3State: false,
                chartsListState: true,
                tableState: false,
                trendChart2Option: null,
                selectData: 'peoplea',
                formInline: {
                    provinceId: '',
                    cityId: '',
                    areaId: '',
                    time: '',
                    provinceName: '',
                    cityName: '',
                    areaName: '',
                    schoolName: '',
                    schoolId: '',
                    timeName: '本月'
                },
                loading: true,
                AnnounceList: [],
                listQuery: {// 分页
                    page: 1,
                    total: 0
                },
                seriseData: [], // 折现的数据
                schoolArr: [],
                timeArrs: [
                    {timeName: '本月', timeId: ''},
                    {timeName: '三个月', timeId: '1'},
                    {timeName: '半年内', timeId: '2'},
                    {timeName: '本年', timeId: '3'}
                ]
            }
        },
        computed: {
            ...mapState({
                config: state => state.config.table
            }),
            ...mapGetters([
                'uid'
            ])
        },
        created() {
            this.getFlyAirData();
           
        },
        
        methods: {
            submit() {
                this.getFlyAirData();
            },
            changeTime(val) {
                let Obj = this.timeArrs.find((item) => {
                    return item.timeId === val;
                });
                this.formInline.timeName=Obj.timeName;
            },
             // 获取学校id
            schoolChange(val) {
                this.formInline.schoolId = val
            },
            // getProvinceName(provinceName) {
            //     this.formInline.provinceName=provinceName;
            // },
            // getCityName(cityName) {
            //     this.formInline.cityName=cityName;
            // },
            // getAreaName(areaName) {
            //     this.formInline.areaName=areaName;
            // },
            // getSchoolName(val) {
            //     let Obj = this.schoolArr.find((item) => {
            //         return item.schoolId === val;
            //     });
            //     this.formInline.schoolName=Obj.schoolName;
            // },
            funFilter() {
                let conditions=[]
                if (this.formInline.provinceName) {
                    conditions.push({'field': 'user.province', 'function': 'equal', 'params': [this.formInline.provinceName]})
                } 
                if (this.formInline.cityName) {
                    conditions.push({'field': 'user.city', 'function': 'equal', 'params': [this.formInline.cityName]});
                }
                if (this.formInline.areaName) {
                    conditions.push({'field': 'user.area', 'function': 'equal', 'params': [this.formInline.areaName]});
                } 
                let filter={'relation': 'and', conditions};
                // 当只有一个查询条件，'relation': 'and'去掉
                if (filter.conditions.length==1) {
                    filter={conditions};
                }
                if (!filter.conditions.length) {// 没有查询条件
                    filter={};
                }
                return filter
            },
            getFlyAirData() {
                this.loading=true;
                this.seriseData=[];// 先清空
                let currentDate=moment(new Date()).format('YYYY-MM-DD');// 当前年月日
                let unit= this.formInline.time==''?'day':'month';// 按月查还是按天
                let from_date='';
                let to_date= currentDate;// 按月查还是按天
                if (!this.formInline.time) {// 本月  从月初-今天
                    from_date=moment(new Date()).format('YYYY-MM-01');
                }
                if (this.formInline.time=='1') {// 三个月
                    from_date=moment(new Date()).months(-3).format('YYYY-MM-DD');
                }
                if (this.formInline.time=='2') {// 半年内
                    from_date=moment(new Date()).months(-6).format('YYYY-MM-DD');
                }
                if (this.formInline.time=='3') {// 本年
                    from_date=moment(new Date()).format('YYYY-01-01');
                }
                let query_id='87';
                let query={
                    'measures': [{'event_name': 'airCoursePaymentSucceed', 'aggregator': 'unique'}],
                    unit, 'sampling_factor': 64, from_date, to_date, 'tType': 'n', 'ratio': 'n', 'approx': false, 
                    'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 
                    filter: this.funFilter(),
                    'detail_and_rollup': true, 'use_cache': true,
                    'request_id': 1515981303662
                };
                let inforSent={
                    query,
                    query_id,
                    real_time: false,
                    type: 'line'// 柱状图
                };
                // detail_result里面取图表的数据，从rollup_result里面取结果
                // 空中课堂开通学校数
                this.openSchoolNum(from_date);
                // 购买总人数
                this.$store.dispatch('getQuery', inforSent).then((data) => {// 87
                    this.loading = false;
                    // let buy = data.data.detail_result.rows.find((item) => {// 取出空中课堂的 购买总人数
                    //     return item.by_values[0] === '空中课堂';
                    // });
                    let buy = data.data.detail_result.rows[0];
                    if (buy) {
                        let buyList=[];
                        buy.values.forEach(vals => {
                            buyList.push(vals[0]);
                        });
                        this.seriseData.push({
                            name: '购买总人数',
                            type: 'line',
                            areaStyle: {normal: {}},
                            stack: '总量',
                            data: buyList
                        });
                    }
                    let buyTotle = data.data.rollup_result.rows.find((item) => {// 取出空中课堂的 观看总次数
                        return item.by_values[0] === '空中课堂';
                    });
                    this.buyNum=0;
                    if (buyTotle) {
                        this.buyNum=buyTotle.values[0][0];// 总数
                    }

                // 观看总次数
                    inforSent.query={'measures': [{'event_name': 'finishWatchCourseVideo', 'aggregator': 'unique'}],
                        unit, 'by_fields': ['event.finishWatchCourseVideo.contentType'], 'sampling_factor': 64, 
                        from_date, to_date, 'tType': 'n', 'ratio': 'n', 'approx': false, 
                        'axis_config': {'isNormalize': false, 'left': [], 'right': []}, filter: this.funFilter(),
                        'detail_and_rollup': true, 'use_cache': true,
                        'request_id': 1515981604776};
                    inforSent.query_id='88' 
                    this.$store.dispatch('getQuery', inforSent).then((data) => {// 88
                        this.loading = false;
                        let view = data.data.detail_result.rows.find((item) => {// 取出空中课堂的 观看总次数
                            return item.by_values[0] === '空中课堂';
                        });
                        if (view) {
                            let viewList=[];
                            view.values.forEach(vals => {
                                viewList.push(vals[0])
                               
                            });
                            this.seriseData.push({
                                name: '观看总次数',
                                type: 'line',
                                areaStyle: {normal: {}},
                                stack: '总量',
                                data: viewList
                            });
                        }
                        let viewTotle = data.data.rollup_result.rows.find((item) => {// 取出空中课堂的 观看总次数
                            return item.by_values[0] === '空中课堂';
                        });
                        this.viewNum0=0;
                        if (viewTotle) {
                            this.viewNum=viewTotle.values[0][0];// 总数
                        }


                       // 观看总时长
                        inforSent.query={'measures': [{'event_name': 'finishWatchCourseVideo', 'aggregator': 'SUM', 
                            'field': 'event.finishWatchCourseVideo.contentWatchDuration'}], 
                            unit, 'by_fields': ['event.finishWatchCourseVideo.contentType'], 
                            'sampling_factor': 64, from_date, to_date, 'tType': 'n', 'ratio': 'n', 'approx': false, 
                            'axis_config': {'isNormalize': false, 'left': [], 'right': []}, filter: this.funFilter(), 
                            'detail_and_rollup': true, 'use_cache': true,
                            'request_id': 1515981690811};
                        inforSent.query_id='89' 

                        this.$store.dispatch('getQuery', inforSent).then((data) => {// 89
                            this.loading = false;
                            // let timeTotle = data.data.detail_result.rows.find((item) => {// 取出空中课堂的 观看总次数
                            //     return item.by_values[0] === '空中课堂';
                            // });
                            // if (timeTotle) {
                            //     let timeTotleList=[];
                            //     timeTotle.values.forEach(vals => {
                            //         timeTotleList.push(vals[0])
                            //     });
                            //     this.seriseData.push({
                            //         name: '观看总时长',
                            //         type: 'line',
                            //         stack: '总量',
                            //         areaStyle: {normal: {}},
                            //         data: timeTotleList
                            //     });
                            // }
                            let timeTotleNum = data.data.rollup_result.rows.find((item) => {// 取出空中课堂的 观看总次数
                                return item.by_values[0] === '空中课堂';
                            });
                            this.viewTime=0;
                            if (timeTotleNum) {
                                this.viewTime=this.formatDuring(timeTotleNum.values[0][0])
                            }
                            this.trendChart2Option = {
                                tooltip: {
                                    trigger: 'axis',
                                    axisPointer: {
                                        type: 'cross',
                                        label: {
                                            backgroundColor: '#6a7985'
                                        }
                                    }
                                },
                                color: ['#7BC0F2', '#2EC7C9', '#FFB980', '#B6A2DE', '#D87A80'],
                                legend: {
                                    data: ['开通学校数', '购买总人数', '观看总次数']
                                },
                                toolbox: {
                                    feature: {
                                        saveAsImage: {}
                                    }
                                },
                                grid: {
                                    left: '3%',
                                    right: '4%',
                                    bottom: '3%',
                                    containLabel: true
                                },
                                xAxis: [
                                    {
                                        type: 'category',
                                        boundaryGap: false,
                                        data: data.xAxisData
                                    }
                                ],
                                yAxis: [
                                    {
                                        type: 'value'
                                    }
                                ],
                                series: this.seriseData
                            };
                        })

                    })
                })
            },
            // 空中课堂开通学校数
            openSchoolNum(from_date) {
                let query_id=110,
                    show_list=false, // true 返回表记录数据
                    type='event',
                    real_time=false;  
                let query={
                    province: this.formInline.provinceName,
                    city: this.formInline.cityName,
                    area: this.formInline.areaName,
                    schoolName: this.formInline.schoolId,
                    from_date
                };
                queryTable(query, query_id, undefined, undefined, show_list, type, real_time).then(res => {
                    this.loading = false;
                    // 开通学校数
                    let dataList=[];
                    this.schoolNum=0;
                    if (res.data.content.rows.length) {

                        res.data.content.rows.forEach(val => {
                            dataList.push(val.co);
                            this.schoolNum+=val.co// 开通学校数统计总数
                        });
                        this.seriseData.push({
                            name: '开通学校数',
                            type: 'line',
                            stack: '总量',
                            areaStyle: {normal: {}},
                            data: dataList
                        });
                    } else {
                        return 
                    }
                }).catch(() => {
                    // this.loading = false;
                    // this.loadingChart = false;
                });
            },
            // 把秒转成天时分秒
            formatDuring(second) {
                var days = parseInt(second / (60 * 60 * 24));
                var hours = parseInt((second % (60 * 60 * 24)) / (60 * 60));
                var minutes = parseInt((second % (60 * 60)) / (60));
                var seconds = second % 60;
                return days + ' 天 ' + hours + ' 时 ' + minutes + ' 分 ' + seconds + ' 秒 ';
            }
        }
    }
</script>
<style lang="scss" scoped>
    .main-content {
         position: relative;
        padding: 20px 20px 10px;
        width: 1400px;
        margin: 0 auto;
        .echartsLayout-content .data-list .data-item .item .title {
            margin-left:80px;
            margin-top:62px;
        }
        .echartsLayout-content .data-list .data-item .item .data {
            margin-left: 80px;
             margin-top:46px;
        }
        .echartsLayout-content .data-list .data-item .item .dataLong {
            font-size: 22px;
        }
        .dataTime {
            font-size: 36px;
        }
    }
</style>                     